/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function (headA, headB, skipA, skipB) {
  skipA = typeof skipA === 'undefined' ? 0 : skipA;
  skipB = typeof skipB === 'undefined' ? 0 : skipB;
  let headAList = [];
  let headBList = [];
  while (headA.next) {
    headAList.push(headA);
    headA = headA.next;
  }
  headAList.push(headA);
  while (headB.next) {
    headBList.push(headB);
    headB = headB.next;
  }
  headBList.push(headB);
  headAList.splice(0, skipA); 
  headBList.splice(0, skipB); 
  let len1 = headAList.length;
  let len2 = headBList.length;

  console.log(headBList, headAList)

  let max = Math.max(len1, len2);
  let j;
  for (j = max - 1; j >= 0; j--) {
    let A = headAList[j].val;
    let B = headBList[j].val;
    if(j)
    if (A === B) {
      continue;
    } else {
      break;
    }
  }
  return headAList[j + 1]
};

let link1 = {
  val: 4,
  next: {
    val: 1,
    next: {
      val: 8,
      next: {
        val: 4,
        next: {
          val: 5
        }
      }
    }
  }
}
let link2 = {
  val: 5,
  next: {
    val: 0,
    next: {
      val: 1,
      next: {
        val: 8,
        next: {
          val: 4,
          next: {
            val: 5
          }
        }
      }
    }
  }
}
console.log(getIntersectionNode(link1, link2, 2, 3));